import React, { useState, useEffect } from 'react';
import { Link, Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import { Button, Dropdown, Space } from 'antd';
import './../style/main.css';
import './../style/kuangjia.css';
import './../style/zhanghu.css';
import { useGlobalContext } from './GlobalContext';
import logo from '../img/logo.svg'
import Recommend from './online/Recommend';
import Playhall from './online/PlayHall';
import MusicVideo from './online/MusicVideo';
import Favormusic from './mymusic/favormusic';
import Recentplay from './mymusic/recentplay'
import Localmusic from './mymusic/localmusic';
import MusicSearch from './songLists/MusicSearch';
import MusicPlayer from './Player/MusicPlayer';
import Playlist from './songLists/Playlist';
import DayRecommend from './songLists/DayRecommend';
import WelcomIndex from './WelcomeIndex';
import ProfileModal from './tanchuang.jsx/ProfileModal';
import Musiclyric from './Player/musiclyric';
import PlayerLists from './songLists/PlayerLists';
import PersonalSonglist from './songLists/PersonalSonglist';
import EditPersonalsonglist from './songLists/EditPersonalsonglist';
import PersonalsonglistDelete from './tanchuang.jsx/PersonalsonglistDelete';
import FavorsonglistDelete from './tanchuang.jsx/FavorsonglistDelete';
import axios from '../API'; // 自定义的 axios 实例
const MusicApp = () => {
  const { userId, setUserId, persongListrefresh, setPerSonglistRefresh, favsongListrefresh, setFavSonglistRefresh } = useGlobalContext();
  const [activePage, setActivePage] = useState('personalSonglist');
  const showPage = (page) => {
    setActivePage(page);
  }

  const [favorSonglist, setFavorSonglist] = useState([])

  useEffect(() => {
    fetch(`http://localhost:8088/favlist/userall/${userId}`)
      .then((response) => response.json())
      .then((data) => {
        setFavorSonglist(data.data)
      })
      .catch((error) => {
        console.error('Error fetching song data:', error);
      })
  }, [favsongListrefresh, userId])

  const [personalSonglist, setPersonalSonglist] = useState([])
  useEffect(() => {
    fetch(`http://localhost:8088/songlist/all/${userId}`)
      .then((response) => response.json())
      .then((data) => {
        setPersonalSonglist(data.data)
      })
      .catch((error) => {
        console.error('Error fetching song data:', error);
      })
  }, [persongListrefresh, userId])

  //新建歌单
  const handleNewsonglistclick = async () => {
    try {
      const response = await fetch("http://localhost:8088/songlist", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to update newsonglist status");
      }
      setPerSonglistRefresh(!persongListrefresh)
    } catch (error) {
      console.error("Error handling Newsonglist request: ", error);
    }
  }
  //删除歌单
  const [songlistId, setSonglistId] = useState('')
  const [favsonglistId, setFavSonglistId] = useState('')
  const [delwindowVisible, setdelwindowVisible] = useState(false)
  const [delwindowVisible2, setdelwindowVisible2] = useState(false)
  const delpersonlis = (songlistId) => {
    setdelwindowVisible(true)
    setSonglistId(songlistId)
  }
  const delpersonlis2 = (songlistId) => {
    setdelwindowVisible2(true)
    setFavSonglistId(songlistId)
  }
  const handledelwindowVisible = (visible) => {
    setdelwindowVisible(visible);
    setPerSonglistRefresh(!persongListrefresh);
  };

  const handledelwindowVisible2 = (visible) => {
    setdelwindowVisible2(visible);
    setFavSonglistRefresh(!favsongListrefresh);
  };

  const [showProfile, setShowProfile] = useState(false);
  const [isLyricVisible, setIsLyricVisible] = useState(false);
  const [keyword, setKeyword] = useState('');
  const [songs, setSongs] = useState([]);
  const [currentSong, setCurrentSong] = useState({});
  const [previousPath, setPreviousPath] = useState(null);
  const [loading, setLoading] = useState(false);  // 控制加载状态
  const [curTim, setCurTim] = useState(0);
  const navigate = useNavigate();
  const location = useLocation(); // 获取 location 对象
  // const { userId, userNickname } = location.state || {};  //登录页获取到的用户信息
  const [avatar, setAvatar] = useState('src/img/avatar.jpg');
  const [nickname, setNickname] = useState('Denselin');

  useEffect(() => {
    if (userId) {
      axios.get(`/api/user/info/${userId}`)
        .then(response => {
          const userInfo = response.data.data;
          console.log("Fetched User Info:", userInfo);
          // const fullAvatarUrl = getAvatarUrl(userInfo.avatar);
          setAvatar(userInfo.avatar || 'src/img/avatar.jpg');
          setNickname(userInfo.nickname || 'Denselin');
        })
        .catch(error => {
          console.error("Error fetching user info:", error);
        });
    }
  }, [userId]);
  const updateAvatar = (newAvatar, newNickname) => {
    setAvatar(newAvatar);
    setNickname(newNickname);
  };
  const handleAvatarClick = () => {
    setShowProfile(true);   //打开 ProfileModal
  };


  const closeProfileModal = () => {
    setShowProfile(false);
  };

  const handleLyricVisibilityChange = (visible) => {
    setIsLyricVisible(visible);
  };

  const handleSearch = async () => {
    setLoading(true);  // 开始加载数据时显示加载动画
    try {
      const response = await fetch(`http://localhost:3000/search?keywords=${keyword}&limit=100`);
      const data = await response.json();

      if (data.result && data.result.songs) {
        const songIds = data.result.songs.map(song => song.id).join(',');
        const detailsResponse = await fetch(`http://localhost:3000/song/detail?ids=${songIds}`);
        const detailsData = await detailsResponse.json();

        if (detailsData.songs) {
          const songsdata = await Promise.all(detailsData.songs.map(async (song, index) => {
            try {
              const urlResponse = await fetch(`http://localhost:3000/song/url?id=${song.id}`);
              const urlData = await urlResponse.json();

              const playUrl = urlData.data && urlData.data[0] ? urlData.data[0].url : null;

              return {
                musicId: song.id,
                musicName: song.name,
                artName: song.ar[0]?.name || '未知',
                album: song.al.name,
                coverUrl: song.al.picUrl,
                dt: song.dt,
                playUrl: playUrl,
                songIndex: index,
              };
            } catch (urlError) {
              console.error(`Error fetching URL for song ${song.id}: `, urlError);
              return {
                musicId: song.id,
                musicName: song.name,
                artName: song.ar[0]?.name || '未知',
                album: song.al.name,
                coverUrl: song.al.picUrl,
                dt: song.dt,
                playUrl: null,
                songIndex: index,
              };
            }
          }));

          setSongs(songsdata);
          navigate('/musicapp/searchPage');
        } else {
          setSongs([]);
        }
      } else {
        setSongs([]);
      }
    } catch (error) {
      console.error("Error fetching data: ", error);
    } finally {
      setLoading(false);  // 数据加载完成，隐藏加载动画
    }
  };

  const handleKeyDown = (Event) => {
    if (Event.key === 'Enter') {
      handleSearch();
    }
  };

  const handleSongSelect = (song) => {
    setCurrentSong(song);
  };

  const handleBack = () => {
    setPreviousPath(window.location.pathname);
    navigate(-1);
  };

  const handleForward = () => {
    if (previousPath) {
      navigate(previousPath);
    }
  };

  const [playerlisstVisible, setPlayerListVisible] = useState(false)
  const handlePlayerListVisible = () => {
    setPlayerListVisible(!playerlisstVisible);
  }

  const items = ({ songlistId }) => [
    {
      key: '1',
      label: (
        <a onClick={() => delpersonlis(songlistId)}>
          删除
        </a>
      ),
    },
    { key: '2', label: '下载', },
    { key: '3', label: '添加到歌单', },
    { key: '4', label: '添加到播放' },
  ];

  const items2 = ({ songlistId }) => [
    {
      key: '1',
      label: (
        <a onClick={() => delpersonlis2(songlistId)}>
          删除
        </a>
      ),
    },
    { key: '2', label: '下载', },
    { key: '3', label: '添加到歌单', },
    { key: '4', label: '添加到播放' },
  ];

  return (
    <div className="container">
      <div className='play_menu_btn'>
        {/* <i className="ri-volume-up-line"></i> */}
        <i className="ri-menu-line"
          onClick={handlePlayerListVisible}
        ></i>
      </div>
      <div className="main-container">
        <div className="left">
          <div className="logo">
            <img src={logo} alt="logo" />
          </div>
          <div className="onlinemusic">
            <div>
              <p>在线音乐</p>
            </div>
            <ul>
              <Link to="recommend"><li><i className="ri-home-line"></i>推荐</li></Link>
              <Link to="playhall/highlights"><li><i className="ri-cup-line"></i>乐馆</li></Link>
              <Link to="musicvideo"><li><i className="ri-mv-line"></i>视频</li></Link>
            </ul>
          </div>
          <div className="mymusic">
            <div>
              <p>我的音乐</p>
            </div>
            <ul>
              <Link to="favormusic/songs"><li><i className="ri-heart-line"></i>喜欢</li></Link>
              <Link to="recentmusic"><li><i className="ri-time-line"></i>最近播放</li></Link>
              <Link to="localmusic"><li><i className="ri-download-2-line"></i>本地和下载</li></Link>
            </ul>
          </div>
          <div className="myplaylists">
            <div>
              <p className='ss1'>
                <span
                  onClick={() => showPage('personalSonglist')}
                  className={activePage === 'personalSonglist' ? '' : 'clic1'}
                >
                  自建歌单
                </span> | <span
                  onClick={() => showPage('likeSonglist')}
                  className={activePage === 'likeSonglist' ? '' : 'clic1'}
                >
                  收藏歌单
                </span>
                <i
                  className='ri-add-line'
                  onClick={handleNewsonglistclick}></i>
              </p>
            </div>
            {activePage === 'personalSonglist' && (
              <ul >
                {personalSonglist.map((item) => (
                  <div className='personallistli'>
                    <Link
                      to={`personalSonglist/${item.songlistId}`}
                      onContextMenu={(e) => e.preventDefault()} // 阻止 Link 默认行为
                    >
                      <li className='songlistlifont'>
                        <img src={item.coverUrl} alt="img" />
                        {item.songListName}
                      </li>
                    </Link>
                    <div className="menu2">
                      <Space direction="vertical">
                        <Space wrap>
                          <Dropdown
                            menu={{
                              items: items({ songlistId: item.songlistId }), // 动态传入当前歌单的 ID
                            }}
                            placement="topLeft"
                            trigger={['click']}
                          >
                            <i className="ri-menu-4-line"></i>
                          </Dropdown>
                        </Space>
                      </Space>
                    </div>
                  </div>

                ))}
              </ul>
            )}

            {activePage === 'likeSonglist' && (
              <ul>
                {favorSonglist.map((item, index) => (
                  <div className='personallistli'>
                    <Link
                      to={`favorSonglist/${item.songListId}`}
                      onContextMenu={(e) => e.preventDefault()}
                    >
                      <li className='songlistlifont'>
                        <img src={item.coverUrl} alt="img" />
                        {item.songListName}
                      </li>
                    </Link>
                    <div className="menu2">
                      <Space direction="vertical">
                        <Space wrap>
                          <Dropdown
                            menu={{
                              items: items2({ songlistId: item.songListId }), // 动态传入当前歌单的 ID
                            }}
                            placement="topLeft"
                            trigger={['click']}
                          >
                            <i className="ri-menu-4-line"></i>
                          </Dropdown>
                        </Space>
                      </Space>
                    </div>
                  </div>
                ))}
              </ul>
            )}
          </div>
        </div>

        <div className="right">
          <div className="topBar">
            <div className="rh">
              <span className="fowardAndbackon">
                <i className="ri-arrow-left-s-line" onClick={handleBack}></i>
                <i className="ri-arrow-right-s-line" onClick={handleForward}></i>
              </span>
              <div className="seh">
                <div className="search">
                  <i className="ri-search-line"></i>
                  <input
                    type="text"
                    id="searchsongs"
                    placeholder="搜索"
                    value={keyword}
                    onChange={(e) => setKeyword(e.target.value)}
                    onKeyDown={handleKeyDown} />
                </div>
                <span className="listhen"><i className="ri-music-fill"></i></span>
              </div>
            </div>
            <div className="lef">
              <div className="avatar" onClick={handleAvatarClick}>
                <img src={avatar} alt="" />
              </div>
              {showProfile && (
                <ProfileModal
                  onClose={closeProfileModal}
                  isVisible={showProfile}
                  userId={userId}
                  userNickname={nickname}
                  avatar={avatar}  // 将 avatar 传递给 ProfileModalv
                  onAvatarUpdate={updateAvatar}  // 向 ProfileModal 传递回调函数
                />
              )}

              <div className="name">
                <p>{nickname}</p>
              </div>
            </div>
          </div>

          <div className="ma">
            {/* 添加加载动画 */}
            {loading ? (<div className="loadingPage">
              <div className="loadcomponents">
                <div className='loader2'></div>
                <div className='loader1'></div>
              </div>
            </div>) : (
              <Routes>
                <Route path='/' element={<WelcomIndex />} />
                <Route path="favorSonglist/:playlistId" element={<Playlist />} />
                <Route path='/personalSonglist/:playlistId' element={<PersonalSonglist />} />
                <Route path='/personalSonglist/:playlistId/edit' element={<EditPersonalsonglist />} />
                <Route path="recommend/*" element={<Recommend />} />
                <Route path="recommend/:playlistId" element={<Playlist />} />
                <Route path='recommend/dailysongs' element={<DayRecommend />} />
                <Route path="playhall/*" element={<Playhall />} />
                <Route path="playhall/highlights/:playlistId" element={<Playlist />} />
                <Route path="playhall/playlist-categories/:playlistId" element={<Playlist />} />
                <Route path="musicvideo" element={<MusicVideo />} />
                <Route path="favormusic/*" element={<Favormusic />} />
                <Route path='recentmusic' element={<Recentplay />} />
                <Route path="localmusic/*" element={<Localmusic />} />
                <Route path="searchPage" element={<MusicSearch songs={songs} />} />
              </Routes>
            )}

          </div>
        </div>
      </div>
      {isLyricVisible && <Musiclyric
        currentSong={currentSong} curTim={curTim}
        isLyricVisible={isLyricVisible}
        onLyricVisibilityChange={handleLyricVisibilityChange}
      />}
      {playerlisstVisible && <PlayerLists />}
      <MusicPlayer
        playingsong={setCurrentSong}
        setCurTim={setCurTim}
        isLyricVisible={isLyricVisible}
        onLyricVisibilityChange={handleLyricVisibilityChange}
      />
      {delwindowVisible && <PersonalsonglistDelete
        songlistId={songlistId}
        ondelwindowVisibleChange={handledelwindowVisible}
      />}
      {delwindowVisible2 && <FavorsonglistDelete
        songlistId={favsonglistId}
        ondelwindowVisibleChange={handledelwindowVisible2}
      />}
    </div>
  );
};

export default MusicApp;